import datetime
import time

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.shortcuts import redirect
from django.views import View
from django.views.decorators.http import require_http_methods


# Create your views here.


def index(request):
    return JsonResponse({'message': 'Hello World!'}, status=200)


def login(request, name, age):
    print(name)
    print(age)
    return HttpResponse('Hello World! login 登陆成功！')


def datatime_one(request, mather, year):
    print(mather)
    print(year)
    return HttpResponse('datatime one')


# 反向解析
def txt(request):
    path_rest = reverse('yulin', kwargs={'mather': '2024', 'year': '09'})
    # 得到完整的路径   /usertwo/datatime_one/2024/09/
    print(path_rest)
    # return HttpResponse(path_rest)
    # if path_rest:
    #     return HttpResponse(path_rest)
    # 休眠两秒跳转数据
    time.sleep(2)
    return redirect(path_rest)


# 试图函数
class MyView(View):
    # 定义请求方式，这里的请求方式只能是VIEW里面的
    def get(self, request):
        # 这里我们去获取他的请求
        print('1', request.GET)
        print('2', request.POST)
        print('3', request.body)
        return HttpResponse("my_view")

    def post(self, request):
        print('2', request.POST)
        # 这里传入的参数只能是appli/json
        print('3', request.body)
        return HttpResponse("my_view_post")

    def delete(self, request):
        pass


# 定义一个只能由用户设置的参数

@require_http_methods(['GET', 'POST'])
def test04(request):
    print(request.GET)
    print(request.POST)
    return HttpResponse("test04_get")


@require_http_methods(['GET'])
def test05(request):
    # 这里我们主要是用木板数据
    name = "张三"
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return render(request, 'login.html', locals())


@require_http_methods(['GET'])
def test06(request):
    # 获取界面中的数据
    requ_name = request.GET.get('name')
    print(requ_name)
    # return HttpResponse(requ_name)
    try:
        if requ_name:
            print(requ_name)
            return JsonResponse({'name': requ_name})
    except Exception as e:
        return JsonResponse({'error': str(e)})

    return HttpResponse("直接结束没有进去判断")


# tes07 跳到 test06
@require_http_methods(['GET'])
def test07(request):
    print("-------------")
    print(time.sleep(2))
    print('-------------')
    return redirect('/usertwo/hello/')
